package com.zzyl.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.entity.Visit;
import com.zzyl.mapper.CustomerReservationMapper;
import com.zzyl.service.CustomerReservationService;
import com.zzyl.utils.UserThreadLocal;
import com.zzyl.vo.TimeVo;
import com.zzyl.vo.VisitVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Description CustomerReservation
 * @Author Wen Jie
 * @Date 2024-09-14
 */
@Service
public class CustomerReservationServiceImpl implements CustomerReservationService {
    @Autowired
    private CustomerReservationMapper customerReservationMapper;
    @Override
    public void addCustomerReservation(VisitVo visitVo) {
        customerReservationMapper.addCustomerReservation(visitVo);
    }

    @Override
    public PageResponse<VisitVo> selectByPage(Integer pageNum, Integer pageSize,Integer status) {
        PageHelper.startPage(pageNum, pageSize);
        Page<Visit> visits = customerReservationMapper.selectByPage(status);
        PageResponse<VisitVo> pageResponse = PageResponse.of(visits, VisitVo.class);
        return pageResponse;
    }

    @Override
    public void cancel(Long id) {
        customerReservationMapper.cancel(id);
    }

    @Override
    public int cancelledCount() {
        Long userId = UserThreadLocal.getUserId();
        Integer count = customerReservationMapper.cancelledCount(userId);
        if (count == null) {
            return 0;
        }
        return count;
    }

    @Override
    public List<TimeVo> countByTime(Long timestamp) {
        List<TimeVo> countTime = new ArrayList<>();
        //将timestamp格式化
        Date date = new Date(timestamp);
        LocalDateTime currentTime = date.toInstant().atZone(java.time.ZoneId.systemDefault()).toLocalDateTime();
        LocalTime now = currentTime.toLocalTime();
        LocalTime startTime = LocalTime.of(8, 0); // 早上8点
        LocalTime endTime = LocalTime.of(18, 0); // 下午18点
        LocalTime time = startTime;
        while (time.isBefore(endTime) || time.equals(endTime)) {
            if (time.isAfter(now)) {
                LocalDateTime formattedDateTime = LocalDateTime.of(LocalDate.now(), time);
                String formattedTime = formattedDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                Integer count1 = customerReservationMapper.countByTime(formattedTime);
                Integer count = 6 - count1;
                countTime.add(new TimeVo(formattedTime, count));
            }
            time = time.plusMinutes(30); // 增加半小时
        }


        return countTime;
    }
}
